﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XfTechOAWeb.Data;
using XfTechOAWeb.Dtos.TodoItems;
using XfTechOAWeb.IService;
using XfTechOAWeb.Models;
using AutoMapper;
using Microsoft.AspNetCore.Http;
using System.Security.Claims;

namespace XfTechOAWeb.Service
{
    /// <summary>
    /// 待办事项服务实现类
    /// </summary>
    public class TodoItemService : ITodoItemService
    {
        private readonly ITodoItemRepository _todoItemRepository;
        private readonly IMapper _mapper;
        private readonly IHttpContextAccessor _httpContext;

        private int _currentUserID;

        public int CurrentUserId
        {
            get 
            {
                string id = _httpContext.HttpContext.User.FindFirst(x => x.Type == ClaimTypes.NameIdentifier).Value;
                _currentUserID = Convert.ToInt32(id);
                return _currentUserID; 
            }
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="todoItemRepository"></param>
        public TodoItemService(ITodoItemRepository todoItemRepository, 
                               IMapper mapper, 
                               IHttpContextAccessor httpContext)
        {
            _todoItemRepository = todoItemRepository;
            _mapper = mapper;
            _httpContext = httpContext;
        }

        /// <summary>
        /// 获取待办事项
        /// </summary>
        /// <returns></returns>
        public async Task<List<TodoItem>> GetListAsync(int userId)
        {
            return (await _todoItemRepository.GetListAsync(userId)).ToList();
        }

        /// <summary>
        /// 添加待办事项
        /// </summary>
        /// <param name="todoItem"></param>
        /// <returns></returns>
        public async Task<int> InsertAsync(CreateUpdateTodoItemDto todoItem)
        {
            TodoItem item = _mapper.Map<TodoItem>(todoItem);
            item.CreatedTime = DateTime.Now;
            item.CreatedUserID = CurrentUserId;
            return await _todoItemRepository.InsertAsync(item);
        }
    }
}
